#coding:utf-8
import socket
import threading
from multiprocessing import Process, Queue
#import dataParse
import struct
import pymysql
import datetime
import select
import os 

def server(q):
	global address,port,sock 
	address = "0.0.0.0"
	port = 10001
	sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	 
	epoll = select.epoll()  
	#获取创建好的sock的文件描述符  
	fd = sock.fileno()  
	sock.bind((address,port))  
	sock_dict = {}  
	sock_dict[fd] = sock  
	#对该sock进行注册  
	epoll.register(fd,select.EPOLLIN)  
	sock.listen(5)  
	while True:
		events = epoll.poll(1)
		for fileno,event in events:#获取到的文件描述符和sock的相同就说明是一个新的连接
			if fileno == fd:
				(client,address) = sock.accept()
				print (address)
				client.setblocking(0)#将新的连接进行注册，用来接收消息
				epoll.register(client.fileno(),select.EPOLLIN)
				sock_dict[client.fileno()] = client
			elif event & select.EPOLLIN:
				print ("fileno:",fileno)#返回套接字的文件描述符
				data = sock_dict[fileno].recv(128)
				if data == '你好':
					print ("Data:",data.decode('UTF-8') )
					sock_dict[fileno].send("你好")
				elif len(data) == 0:
					print ("client %d is not connected"%fileno )
					epoll.unregister(fileno)
				else:
					print ("收到下层基站来信",data.decode())
					datas =  data.decode()
					#print(type(datas))
					q.put(datas)


def WriteDBProcess(q):
	while True:
		data = q.get()
		print(data)
		
		

def main():
	q = Queue()
	#启动进程server
	prev=Process(target=server, args=(q,))
	#启动京城WriteDB
	ploc=Process(target=WriteDBProcess,args=(q,))
	prev.start()
	ploc.start()

if __name__ == '__main__':
	main()